package en.edu.lzzy.demomvcemployee.service;


import en.edu.lzzy.demomvcemployee.model.Employee;
import en.edu.lzzy.demomvcemployee.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeServiceImpl implements EmployeeService{

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    @Override
    public void saveEmployee(Employee employee) {
        this.employeeRepository.save(employee);
    }

    @Override
    public Employee getEmployeeById(long id) {
        // 调用数据访问层查找指定ID的员工，返回Optional对象
        Optional < Employee > optional = employeeRepository.findById(id);
        Employee employee = null;
        // 如果存在指定id的员工
        if (optional.isPresent()) {
            // 从Optional对象中获取员工对象
            employee = optional.get();
        } else {
            // 否则抛出运行时异常
            throw new RuntimeException(" 找不到员工ID：" + id);
        }
        return employee;
    }

    @Override
    public void deleteEmployeeById(long id) {
        this.employeeRepository.deleteById(id);
    }

}
